import React from 'react';
import { Checkbox } from 'antd';
import { formatMessage } from 'umi';
import classNames from 'classnames';
import Modal from '@/zero/components/Modal';
import Text from './_components/Text';
import styles from './index.less';

/**
 * 多选模式
 */
const Index = (props) => {
  const {
    options = [],

    separator,

    value,
    onChange,
    disabled,

    changeConfirm,

    vertical = false,
    checkAll = false,

    ...rest
  } = props;

  const newValue = (separator ? value?.split(separator) : value) || [];

  const newOnChange = (v) => {
    if (onChange) {
      onChange(separator ? v?.join(separator) : v);
    }
  };

  if (disabled && disabled.render) {
    return <Text value={newValue} options={options} render={disabled.render} />;
  }

  return (
    <>
      {checkAll && (
        <div className={styles.checkAllWrapper}>
          <Checkbox
            checked={newValue.length === options.length}
            indeterminate={newValue.length !== 0 && newValue.length < options.length}
            onChange={(e) => {
              const checkedValue = e.target.checked
                ? options.map((item) => (typeof item === 'object' ? item.value : item))
                : [];
              newOnChange(checkedValue);
            }}
          >
            {checkAll.text || formatMessage({ id: '全选' })}
          </Checkbox>
        </div>
      )}
      <Checkbox.Group
        {...rest}
        disabled={!!disabled}
        value={newValue}
        onChange={(checkedValue) => {
          const push = () => {
            newOnChange(checkedValue);
          };
          if (changeConfirm) {
            const { triggerValues } = changeConfirm;
            if (
              triggerValues === undefined ||
              (triggerValues !== undefined &&
                triggerValues.some((item) => checkedValue?.includes(item)))
            ) {
              Modal.confirm({
                title: 'Bla bla ...',
                content: '',
                ...changeConfirm,
                onOk: push,
              });
              return;
            }
          }
          push();
        }}
      >
        {options.map((item) => (
          <Checkbox
            key={item.value}
            style={{ marginLeft: 0, marginBottom: 6 }}
            {...item}
            className={classNames({ [styles.vertical]: vertical })}
          >
            {item.label}
          </Checkbox>
        ))}
      </Checkbox.Group>
    </>
  );
};

Index.displayName = 'MultipleCheckbox';
export default Index;
